using System;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System.Data;
using System.Web.UI.WebControls;
using cwcare.Modules.cwcareXML.Data;
using System.Linq;
using System.Xml;


namespace cwcare.Modules.cwcareXML
{
    public partial class EditMarker : PortalModuleBase
    {
        private const string InsertMarker = "Insert Marker";
        private const string PathMarkerFile = "~/DesktopModules/cwcareXML/GoogleMap/Markers.xml";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsEditable == false)
            {

                Response.Redirect("~/Default.aspx?TabId=" + this.TabId);
            }
            try
            {
                if (!this.IsPostBack)
                {
                    this.LoadData();
                }
            }
            catch
            { }
        }

        private DataTable LoadXMlFile()
        {
            DataTable dt = new DataTable();
            try
            {
                DataSet ds = new DataSet();
                ds.ReadXml(Server.MapPath(PathMarkerFile));
                dt = ds.Tables["marker"];
            }
            catch { }
            return dt;
        }

        private void UncheckMarkerInit(DataTable dt)
        {
            foreach (DataRow row in dt.Rows)
            {
                row["init"] = "false";
            }
        }

        private void LoadData()
        {
            DataTable dt = this.LoadXMlFile();
            ListItemCollection list = new ListItemCollection();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                list.Add(new ListItem(dt.Rows[i]["name"].ToString(), (i + 1).ToString()));
            }
            ddlMarkers.DataSource = list;
            ddlMarkers.DataTextField = "text";
            ddlMarkers.DataValueField = "value";
            ddlMarkers.DataBind();
            ddlMarkers.Items.Insert(0, InsertMarker);

        }

        protected void ddlMarkers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlMarkers.SelectedIndex != 0)
            {
                try
                {
                    int index = ddlMarkers.SelectedIndex - 1;
                    DataTable dt = this.LoadXMlFile();
                    txtAddress.Text = dt.Rows[index]["address"].ToString();
                    txtPhone.Text = dt.Rows[index]["telephone"].ToString();
                    txtLatitude.Text = dt.Rows[index]["lat"].ToString();
                    txtLongitude.Text = dt.Rows[index]["lng"].ToString();
                    txtName.Text = dt.Rows[index]["name"].ToString();
                    txtType.Text = dt.Rows[index]["type"].ToString();
                    txtType.Text = dt.Rows[index]["state"].ToString();
                    txtType.Text = dt.Rows[index]["city"].ToString();
                    txtType.Text = dt.Rows[index]["county"].ToString();
                    if (dt.Rows[index]["init"].ToString().Equals("true"))
                    {
                        chkInit.Checked = true;
                    }
                    else
                    {
                        chkInit.Checked = false;
                    }
                }
                catch { }
                btnDelete.Visible = true;
            }
            else
            {
                txtAddress.Text = string.Empty;
                txtPhone.Text = string.Empty;
                txtLatitude.Text = string.Empty;
                txtLongitude.Text = string.Empty;
                txtName.Text = string.Empty;
                txtType.Text = string.Empty;
                btnDelete.Visible = false;
            }
        }

        protected void btnCancel_OnClick(object sender, EventArgs e)
        {
            Response.Redirect("~/Default.aspx?TabId=" + this.TabId);
        }

        protected void btnUpdate_OnClick(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = this.LoadXMlFile();
                if (ddlMarkers.SelectedIndex != 0)
                {
                    int index = ddlMarkers.SelectedIndex - 1;

                    dt.Rows[index]["address"] = txtAddress.Text;
                    dt.Rows[index]["telephone"] = txtPhone.Text;
                    dt.Rows[index]["lat"] = txtLatitude.Text;
                    dt.Rows[index]["lng"] = txtLongitude.Text;
                    dt.Rows[index]["name"] = txtName.Text;
                    dt.Rows[index]["type"] = txtType.Text;
                    if (chkInit.Checked)
                    {
                        this.UncheckMarkerInit(dt);
                        dt.Rows[index]["init"] = "true";
                    }
                    else
                    {
                        dt.Rows[index]["init"] = "false";
                    }
                }
                else
                {

                    DataRow row = dt.NewRow();
                    row["address"] = txtAddress.Text;
                    row["telephone"] = txtPhone.Text;
                    row["lat"] = txtLatitude.Text;
                    row["lng"] = txtLongitude.Text;
                    row["name"] = txtName.Text;
                    row["type"] = txtType.Text;
                    if (chkInit.Checked)
                    {
                        this.UncheckMarkerInit(dt);
                        row["init"] = "true";
                    }
                    else
                    {
                        row["init"] = "false";
                    }
                    dt.Rows.Add(row);
                }
                dt.DataSet.WriteXml(Server.MapPath(PathMarkerFile));
            }
            catch { }
            Response.Redirect("~/Default.aspx?TabId=" + this.TabId);
        }
        protected void btnDelete_OnClick(object sender, EventArgs e)
        {
            try
            {
                int index = ddlMarkers.SelectedIndex - 1;
                DataTable dt = this.LoadXMlFile();
                if (dt.Rows[index]["init"].ToString().Equals("true"))
                {

                    if ((index + 1) < dt.Rows.Count)
                    {

                        dt.Rows[index + 1]["init"] = "true";
                    }
                    else if (index > 0)
                    {

                        dt.Rows[index - 1]["init"] = "true";
                    }
                }
                else
                {
                    chkInit.Checked = false;
                }
                dt.Rows.RemoveAt(index);
                dt.DataSet.WriteXml(Server.MapPath(PathMarkerFile));
            }
            catch { }
            Response.Redirect("~/Default.aspx?TabId=" + this.TabId);
        }

        protected void btnSync_OnClick(object sender, EventArgs e)
        {
            mapsDataContext EntityData = new mapsDataContext();

            var entitys = (from a in EntityData.cwc_Locations
                          select a).ToList();
            
            XmlDocument xdoc = new XmlDocument();
            XmlNode xdocNode = xdoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
            xdoc.AppendChild(xdocNode);
            XmlNode xdocRoot = xdoc.CreateElement("markers");
            xdoc.AppendChild(xdocRoot);

            foreach (var location in entitys)
            {
                XmlNode xdocMarker = xdoc.CreateElement("marker");
                xdocRoot.AppendChild(xdocMarker);

                XmlAttribute nameAttr = xdoc.CreateAttribute("name");
                nameAttr.Value = location.address;
                xdocMarker.Attributes.Append(nameAttr);

                XmlAttribute addressAttr = xdoc.CreateAttribute("address");
                addressAttr.Value = location.address;
                xdocMarker.Attributes.Append(addressAttr);

                XmlAttribute telephoneAttr = xdoc.CreateAttribute("telephone");
                telephoneAttr.Value = location.phone;
                xdocMarker.Attributes.Append(telephoneAttr);

                XmlAttribute latAttr = xdoc.CreateAttribute("lat");
                latAttr.Value = location.lattitude;
                xdocMarker.Attributes.Append(latAttr);

                XmlAttribute lngAttr = xdoc.CreateAttribute("lng");
                lngAttr.Value = location.longitude;
                xdocMarker.Attributes.Append(lngAttr);

                XmlAttribute typeAttr = xdoc.CreateAttribute("type");
                typeAttr.Value = "Medical";
                xdocMarker.Attributes.Append(typeAttr);

                XmlAttribute initAttr = xdoc.CreateAttribute("init");
                initAttr.Value = "false";
                xdocMarker.Attributes.Append(initAttr);

                XmlAttribute addIdAttr = xdoc.CreateAttribute("addressID");
                addIdAttr.Value = Convert.ToString(location.addressID);
                xdocMarker.Attributes.Append(addIdAttr);

                XmlAttribute typeCity = xdoc.CreateAttribute("city");
                typeCity.Value = location.city;
                xdocMarker.Attributes.Append(typeCity);

                XmlAttribute typeState = xdoc.CreateAttribute("state");
                typeState.Value = location.state;
                xdocMarker.Attributes.Append(typeState);

                XmlAttribute typeCounty = xdoc.CreateAttribute("county");
                typeCounty.Value = location.county;
                xdocMarker.Attributes.Append(typeCounty);
            }

            try
            {
                xdoc.Save(Server.MapPath(PathMarkerFile));
            }
            catch { }
            Response.Redirect("~/Default.aspx?TabId=" + this.TabId);
        }
    }
}